const pool = require('../tools/getPool');

const sendResponse = require('../tools/sendResponse');

module.exports = function(req, res){

	let oldPassword = req.body.oldPassword;
	let newPassword = req.body.newPassword;

	let account		= req.session.account;
	let type 		= req.body.type;

	if (oldPassword == undefined || newPassword == undefined || account == undefined) {
		sendResponse('error', 'params lack', null, res);
		return;
	}

	pool.getConnection(function(err, connection) {
		if (err) {
			sendResponse('error','database error', null, res);
			return;
		}


		if (type == 'admin') {

			connection.query('SELECT account FROM admin WHERE account = ? and password = ?', [account,oldPassword], function (error, rows, fields) {

				if (error) { 

					sendResponse('error','database error', null, res);
					return;

				} else {

					if (rows.length == 1) {

						connection.query('UPDATE admin SET password = ? WHERE account = ?', [newPassword, account], function (error, rows, fields) {

							connection.release();

							if (error) { 
								if (error.code = "ER_DUP_ENTRY") {
									sendResponse('error','ER_DUP_ENTRY', null, res);
									return;
								} else {
									sendResponse('error','database error', null, res);
									return;
								}
							} else {
								sendResponse('ok','change success', null, res);
								return;
							}

						})

					} else {
						sendResponse('error','password error', null, res);
						return;
					}

				}

			})



		} else if (type == 'clerk') {


			connection.query('SELECT account FROM clerk WHERE account = ? and password = ?', [account,oldPassword], function (error, rows, fields) {

				if (error) { 

					sendResponse('error','database error', null, res);
					return;

				} else {

					if (rows.length == 1) {

						connection.query('UPDATE clerk SET password = ? WHERE account = ?', [newPassword, account],  function (error, rows, fields) {

							connection.release();

							if (error) { 
								console.log(error);
								if (error.code = "ER_DUP_ENTRY") {
									sendResponse('error','ER_DUP_ENTRY', null, res);
									return;
								} else {
									sendResponse('error','database error', null, res);
									return;
								}
							} else {
								sendResponse('ok','change success', null, res);
								return;
							}

						})

					} else {
						sendResponse('error','password error', null, res);
						return;
					}

				}

			})

		} else {

			sendResponse('error','params error', null, res);
			return;

		}



	});

}